<template>
  <div>
    <el-card>
      <div class="card-wrap">
        <el-page-header @back="goBack(false)" content="创建备案项目">
        </el-page-header>
        <div v-if="!isApproval">
          <el-button @click="goBack(false)">取消</el-button>
          <el-button
            type="primary"
            :loading="state.saveLoading"
            @click="handleSave(true, '1')"
            >保存</el-button
          >
          <el-button
            type="primary"
            :loading="state.saveLoading"
            @click="handleSubmit"
            >提交</el-button
          >
        </div>
      </div>
    </el-card>
    <br />
    <el-form
      :disabled="isApproval"
      :model="state.formData"
      ref="formRef"
      @submit.prevent
      :rules="formRules"
      label-width="140px"
    >
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目基础信息</span>
            <div v-if="show1" @click="show1 = !show1" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show1 = !show1" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <el-collapse-transition>
          <div v-show="show1">
            <el-row v-if="showProjectNumber">
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目状态" prop="stageStatus">
                  <el-select
                    v-model="state.formData.stageStatus"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in projectStatusList"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item.dicCode"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input
                    v-model.trim="state.formData.projectName"
                    class="width-custom"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :xl="8" :lg="12" v-if="showProjectNumber">
                <el-form-item label="项目编号">
                  <el-input
                    disabled
                    v-model.trim="state.formData.projectCode"
                    class="width-custom"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :xl="8" :lg="12" v-if="!showProjectNumber">
                <el-form-item label="项目状态" prop="stageStatus">
                  <el-select
                    v-model="state.formData.stageStatus"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in projectStatusList"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item.dicCode"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!--
            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目审批类型" prop="approveTypeMaxCode">
                  <el-select
                    v-model="state.formData.approveTypeMaxCode"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in projectApproveTypeArr"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xl="8" :lg="12" class="approve-code">
                <el-form-item label="" prop="approveTypeMinCode">
                  <el-select
                    v-model="state.formData.approveTypeMinCode"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in projectApproveTypeArr2"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row> -->

            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目开始时间" prop="ext1">
                  <el-date-picker
                    style="width: 100%"
                    v-model="state.formData.ext1"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    type="date"
                  />
                </el-form-item>
              </el-col>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目预计验收时间" prop="ext2">
                  <el-date-picker
                    style="width: 100%"
                    v-model="state.formData.ext2"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    type="date"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目类型" prop="projectTypeCode">
                  <el-select
                    v-model="state.formData.projectTypeCode"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in projectTypeArr"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xl="8" :lg="12">
                <el-form-item label="所属公司主体" prop="principalCompanyCode">
                  <el-select
                    v-model="state.formData.principalCompanyCode"
                    clearable
                    style="width: 100%"
                    value-key="dicCode"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in principalCompanyArr"
                      :key="item.dicCode"
                      :label="item.dicValue"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目负责人" prop="projectLeaderId">
                  <el-select
                    v-model="state.formData.projectLeaderId"
                    style="width: 100%"
                    filterable
                    clearable
                    remote
                    placeholder="请输入姓名搜索"
                    :remote-method="getTableLeaderData"
                    value-key="id"
                    @change="changeLeader"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in userList"
                      :key="item.id"
                      :label="item.name"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xl="8" :lg="12">
                <el-form-item label="项目联系人" prop="projectOwner">
                  <el-select
                    v-model="state.formData.projectOwner"
                    style="width: 100%"
                    filterable
                    clearable
                    remote
                    placeholder="请输入姓名搜索"
                    :remote-method="getTableLeaderData2"
                    value-key="id"
                    @change="changeOwner"
                  >
                    <el-option
                      id="default-option"
                      v-for="item in userList2"
                      :key="item.id"
                      :label="item.name"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="8" :lg="12">
                <el-row>
                  <el-col :xl="4" :lg="4"></el-col>
                  <el-col
                    :xl="8"
                    :lg="8"
                    v-if="state.formData.projectLeaderPhone"
                  >
                    <p class="p-text">
                      电话：{{ state.formData.projectLeaderPhone }}
                    </p>
                  </el-col>
                  <el-col :span="12" v-if="state.formData.projectLeaderEmail">
                    <p class="p-text">
                      邮箱：{{ state.formData.projectLeaderEmail }}
                    </p>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :xl="8" :lg="12">
                <el-row>
                  <el-col :xl="4" :lg="4"></el-col>
                  <el-col
                    :xl="8"
                    :lg="8"
                    v-if="state.formData.projectContactPhone"
                  >
                    <p class="p-text">
                      电话：{{ state.formData.projectContactPhone }}
                    </p>
                  </el-col>
                  <el-col :span="8" v-if="state.formData.projectContactEmail">
                    <p class="p-text">
                      邮箱：{{ state.formData.projectContactEmail }}
                    </p>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <el-row v-if="state.formData.generalBudget">
              <el-col :xl="8" :lg="12">
                <el-form-item label="项目总预算">
                  <el-input disabled v-model="state.formData.generalBudget">
                    <template #append>万元（人名币）</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :xl="8" :lg="12">
                <el-form-item label="其中，已投入">
                  <el-input disabled v-model="state.formData.investmentAmount">
                    <template #append>万元（人名币）</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row>
              <el-col :span="10">
                <el-form-item label=" 是否含可行性研究" prop="isFsbStudy">
                  <el-radio-group v-model="state.formData.isFsbStudy">
                    <el-radio label="1" size="small"> 是</el-radio>
                    <el-radio label="0" size="small">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row> -->
            <el-row>
              <el-col :xl="16" :lg="24">
                <el-form-item label="项目立项书" prop="projectProposalArr">
                  <ecm-upload
                    :files="defaultProposaFileList"
                    :docid="state.docid"
                    @setFile="handleProposaSuccess"
                  >
                    <!-- <template #temp>
                      <el-link
                        v-if="
                          state.formData.approveTypeMaxCode &&
                          state.formData.approveTypeMaxCode.dicCode !== '4'
                        "
                        style="margin-left: 16px"
                        type="primary"
                        @click="
                          postDownload('研发项目申报书（简化版）-模版.docx')
                        "
                        >研发项目申报书（简化版）-模版.docx
                      </el-link>
                      <el-link
                        v-if="
                          state.formData.approveTypeMaxCode &&
                          state.formData.approveTypeMaxCode.dicCode === '4'
                        "
                        style="margin-left: 16px"
                        type="primary"
                        @click="
                          postDownload('预研项目申报书（简化版）-模版.docx')
                        "
                        >预研项目申报书（简化版）-模版.docx
                      </el-link>
                    </template> -->
                  </ecm-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="16" :lg="24">
                <el-form-item label="项目其他申报材料" prop="kyFiles">
                  <ecm-upload
                    :files="defaultFileList"
                    :docid="state.docid"
                    @setFile="handleSuccess"
                  ></ecm-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-collapse-transition>
      </el-card>
      <br />
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目各阶段信息</span>
            <div v-if="show2" @click="show2 = !show2" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show2 = !show2" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <el-collapse-transition>
          <div v-show="show2" class="steps">
            <el-tabs v-model="state.activeStep">
              <el-tab-pane label="可行性研究" name="0">
                <el-row>
                  <el-col :xl="16" :lg="24">
                    <el-form-item label="可行性报告">
                      <ecm-upload
                        :files="defaultkxxFileList"
                        :docid="state.docid"
                        @setFile="kxxHandleSuccess"
                      ></ecm-upload>
                    </el-form-item>
                    <el-form-item label="备注">
                      <el-input
                        type="textarea"
                        v-model.trim="state.formData.filgsKyDesc"
                        class="width-custom"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="立项" name="1">
                <el-row>
                  <el-col :xl="16" :lg="24">
                    <el-form-item label="立项文档" prop="filgsLxFilesArr">
                      <ecm-upload
                        :files="defaultLXFileList"
                        :docid="state.docid"
                        @setFile="lxHandleSuccess"
                      ></ecm-upload>
                    </el-form-item>
                    <el-form-item label="备注">
                      <el-input
                        type="textarea"
                        v-model.trim="state.formData.filgsLxDesc"
                        class="width-custom"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="实施" name="2">
                <el-row>
                  <el-col :xl="16" :lg="24">
                    <el-form-item label="实施文档">
                      <ecm-upload
                        :files="defaultSSFileList"
                        :docid="state.docid"
                        @setFile="ssHandleSuccess"
                      ></ecm-upload>
                    </el-form-item>
                    <el-form-item label="备注">
                      <el-input
                        type="textarea"
                        v-model.trim="state.formData.filgsSsDesc"
                        class="width-custom"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="验收" name="3">
                <el-row>
                  <el-col :xl="16" :lg="24">
                    <el-form-item label="验收文档" prop="filgsYsFilesArr">
                      <ecm-upload
                        :files="defaultYSFileList"
                        :docid="state.docid"
                        @setFile="ysHandleSuccess"
                      ></ecm-upload>
                    </el-form-item>
                    <el-form-item label="备注">
                      <el-input
                        type="textarea"
                        v-model.trim="state.formData.filgsYsDesc"
                        class="width-custom"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="科研成果">
                      <el-select
                        v-model="state.scientifics"
                        clearable
                        filterable
                        multiple
                        placeholder="请输入科研名称"
                        @change="handlePublicscientific"
                        :remote-method="getScientific"
                        style="width: 100%"
                        remote
                      >
                        <el-option
                          v-for="item in state.scientificList"
                          :key="item.id"
                          :label="item.kyName"
                          :value="item.id"
                        ></el-option>
                      </el-select>
                      <el-table
                        v-if="state.scientificTableList.length > 0"
                        :data="state.scientificTableList"
                        border
                        :header-cell-style="{
                          background: '#eef1f6',
                          color: '#606266'
                        }"
                      >
                        <el-table-column type="index" label="序号" />
                        <el-table-column prop="kyNum" label="编号">
                        </el-table-column>
                        <el-table-column prop="kyName" label="成果名称">
                        </el-table-column>

                        <el-table-column label="成果来源">
                          <template #default="{ row }">
                            {{ row.kyTypeName || "其他" }}
                          </template>
                        </el-table-column>
                        <el-table-column label="附件">
                          <template #default="{ row }">
                            <el-link
                              v-for="(item, index) in row.kyAttachmentArr"
                              :key="index"
                              @click="handlePreview(item)"
                              >{{ item.fileName }}</el-link
                            >
                          </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" width="80">
                          <template #default="{ row }">
                            <el-button
                              type="text"
                              size="small"
                              @click="jump(row)"
                              >查看详情</el-button
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="后评价" name="4">
                <el-row>
                  <el-col :xl="16" :lg="24">
                    <el-form-item label="后评价文档">
                      <ecm-upload
                        :files="defaultHPJFileList"
                        :docid="state.docid"
                        @setFile="hpjHandleSuccess"
                      ></ecm-upload>
                    </el-form-item>
                    <el-form-item label="备注">
                      <el-input
                        type="textarea"
                        v-model.trim="state.formData.filgsHpjDesc"
                        class="width-custom"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-collapse-transition>
      </el-card>
      <br />
      <el-card v-if="route.query.instanceId">
        <template #header>
          <div class="card-box-header">
            <span> 流程状态</span>
            <div v-if="show5" @click="show5 = !show5" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show5 = !show5" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-if="steps && steps.length">
          <el-collapse-transition>
            <status-info :currentStep="currentStep" :steps="steps" />
          </el-collapse-transition>
        </div>
      </el-card>
      <br />
      <el-card v-if="route.query.instanceId">
        <template #header>
          <div class="card-box-header">
            <span> 流转记录</span>
            <div v-if="show6" @click="show6 = !show6" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show6 = !show6" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show6">
          <el-collapse-transition>
            <approval-info :activities="approveRecord" />
          </el-collapse-transition>
        </div>
      </el-card>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, unref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { cloneDeep } from "lodash-es";
import {
  postProjectAdd,
  getProjectInfo,
  postProjectUpdate,
  flowSubmit,
  approveProject,
  flowStart,
  submitStage,
  getApproveHistory
} from "/@/api/project";
import { getUsersForScience } from "/@/api/user";
import { postDictList } from "/@/api/common";
import NotifMessage from "/@/utils/message/notification";
import { postScientificList } from "/@/api/scientific";
import { storageLocal } from "/@/utils/storage";
import { flowStatusObj } from "/@/components/StatusInfo/type";
import StatusInfo from "/@/components/StatusInfo/index.vue";
import ApprovalInfo from "/@/components/ApprovalInfo/index.vue";
import EcmUpload from "/@/components/ecmUpload/index.vue";

let defaultFileList = ref([]);
let defaultkxxFileList = ref([]);
let defaultLXFileList = ref([]);
let defaultProposaFileList = ref([]);
let defaultSSFileList = ref([]);
let defaultYSFileList = ref([]);
let defaultHPJFileList = ref([]);
const steps = ref([]);
const formRef = ref<HTMLFormElement | null>(null) as any;
const approveRecord = ref([]);
const router = useRouter();
const route = useRoute();

let showProjectNumber = ref<boolean>(false);
let show1 = ref<boolean>(true);
let show2 = ref<boolean>(true);
let show5 = ref<boolean>(true);
let show6 = ref<boolean>(true);
const currentStep = ref(null);
// let show6 = ref<boolean>(true);
let state: any = reactive({
  docid: window["ecmDocType"].project,
  scientifics: [],
  scientificTableList: [],
  scientificList: [],
  activeStep: 0,
  reason: "", //变更原因
  changeflowType: "2028",
  flowType: "2028",
  changeDialogFormVisible: false,
  isSubmit: false,
  changeInfo: null,
  stopInfo: null,
  saveLoading: false,
  projectManageId: null,
  formData: {
    stageStatus: null,
    generalBudget: null,
    investmentAmount: null,
    filgsHpjDesc: "",
    filgsYsDesc: "",
    filgsLxDesc: "",
    filgsSsDesc: "",
    filgsKyDesc: "",
    saveStatus: "",
    projectName: "",
    projectCode: "",
    projectTypeCode: null,
    projectTypeName: "",
    projectLeaderId: null,
    projectLeaderName: "",
    projectContractDTOList: [],
    projectMemberList: [{}, {}],
    projectOwner: null,
    ext1: "", // 项目开始时间
    ext2: "", // 项目结束时间
    ext3: "", // 项目联系人id
    ext4: "", // 项目联系人name
    ext5: null, // 实际经费
    projectLeaderPhone: "",
    projectLeaderEmail: "",
    projectContactPhone: "",
    projectContactEmail: "",
    kyFiles: [],
    filgsKyFilesArr: [],
    projectProposalArr: [],
    filgsLxFilesArr: [],
    filgsSsFilesArr: [],
    filgsYsFilesArr: [],
    filgsHpjFilesArr: [],
    approvalTypeName: "",
    isFsbStudy: "1",
    principalCompanyCode: null,
    approveTypeMaxCode: null,
    approveTypeMinCode: null
  },
  leaderId: "",
  ownerId: ""
});

let projectTypeArr = ref([]);
let projectApproveTypeArr = ref([]);
let projectApproveTypeArr2 = ref([]);
let principalCompanyArr = ref([]);
let projectStatusList = ref([]);
let userList = ref([]);
let userList2 = ref([]);

const formRules = ref({
  projectName: [{ required: true, message: "请输入名称", trigger: "change" }],
  projectTypeCode: [
    { required: true, message: "请选择类型", trigger: "change" }
  ],
  projectLeaderId: [
    { required: true, message: "请选择负责人", trigger: "change" }
  ],

  projectOwner: [
    { required: true, message: "请选择联系人", trigger: "change" }
  ],
  ext1: [{ required: true, message: "请选择项目开始时间", trigger: "change" }],
  ext2: [
    { required: true, message: "请选择项目预计验收时间", trigger: "change" }
  ],

  approveTypeMaxCode: [
    { required: true, message: "请选择项目审批类型", trigger: "change" }
  ],
  approveTypeMinCode: [
    { required: true, message: "请选择项目审批类型", trigger: "change" }
  ],
  // filgsYsFilesArr: [
  //   { required: true, message: "请上传验收文档", trigger: "change" }
  // ],
  filgsLxFilesArr: [
    { required: true, message: "请上传立项文档", trigger: "change" }
  ],
  // isFsbStudy: [
  //   { required: true, message: "请选择是否含可行性研究", trigger: "change" }
  // ],
  principalCompanyCode: [
    { required: true, message: "请选择所属公司主体", trigger: "change" }
  ]
});

const flowStartData = reactive({
  formBaseInfo: {
    billName: "",
    projectName: "",
    projectManageId: route.query.id,
    id: route.query.id,
    flowStartAttachmentArr: []
  },
  flowFormData: {
    businessId: route.query.id,
    flowTypeCode: "",
    nodeId: route.query.nodeId,
    projectManageId: route.query.id,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "0",
    flowType: "",
    assignee: null,
    opinion: ""
  }
});

const flowPassData = reactive({
  formBaseInfo: {
    id: route.query.id,
    acceptUsers: null
  },
  flowFormData: {
    approvalComments: "",
    approvalResult: "",
    businessId: route.query.id,
    flowId: route.query.flowId,
    flowTypeCode: "",
    instanceId: route.query.instanceId,
    nodeId: route.query.nodeId,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "0",
    flowType: "",
    nodeId: route.query.nodeId,
    procInstId: route.query.instanceId,
    taskId: route.query.taskId,
    opinion: "",
    assignee: null,
    isChargehand: "1", //1：向下提交到下一步：0：回退到某一步
    specialReject: "0"
  },
  tmpStorage: {
    nodeId: route.query.nodeId,
    flowId: route.query.flowId,
    taskId: route.query.taskId,
    handlerId: null,
    valueJson: ""
  }
});

const getStep = () => {
  const nodeId = route.query.nodeId ? route.query.nodeId : "ACT_010";
  steps.value = flowStatusObj[state.flowType];
  if (steps.value && steps.value.length) {
    steps.value.forEach((item, index) => {
      if (item.nodeId === nodeId) {
        currentStep.value = Number(index);
      }
    });
  }
};
const handlePublicscientific = item => {
  state.scientificTableList = [];
  item.forEach(el => {
    const target = state.scientificList.find(obj => obj.id === el);
    target.kyAttachmentArr =
      target.kyAttachmentArr == null ? [] : target.kyAttachmentArr;
    // if (target.kyAttachmentArr) {
    target.kyAttachmentArr.map(el => {
      el["name"] = el.fileName;
    });
    // }

    state.scientificTableList.push(target);
  });
};

// const postDownload = fileName => {
//   window.open(`${location.origin}${location.pathname}/${fileName}`);
// };

const handleSuccess = res => {
  defaultFileList.value = res.file;
  state.formData.kyFiles = res.file;
  formRef.value.clearValidate();
};
const kxxHandleSuccess = res => {
  // if (res.code === 200) {
  //   nextTick(() => {
  defaultkxxFileList.value = res.file;
  state.formData.filgsKyFilesArr = res.file;
  //   });
  // }
  formRef.value.clearValidate();
};
const lxHandleSuccess = res => {
  // if (res.code === 200) {
  //   nextTick(() => {
  defaultLXFileList.value = res.file;
  state.formData.filgsLxFilesArr = res.file;
  //   });
  // }
  formRef.value.clearValidate();
};
const ssHandleSuccess = res => {
  // if (res.code === 200) {
  //   nextTick(() => {
  defaultSSFileList.value = res.file;
  state.formData.filgsSsFilesArr = res.file;
  //   });
  // }
  formRef.value.clearValidate();
};
const ysHandleSuccess = res => {
  // if (res.code === 200) {
  //   nextTick(() => {
  defaultYSFileList.value = res.file;
  state.formData.filgsYsFilesArr = res.file;
  //   });
  // }
  formRef.value.clearValidate();
};
const hpjHandleSuccess = res => {
  // if (res.code === 200) {
  //   nextTick(() => {
  defaultHPJFileList.value = res.file;
  state.formData.filgsHpjFilesArr = res.file;
  //   });
  // }
  formRef.value.clearValidate();
};

const handleProposaSuccess = res => {
  defaultProposaFileList.value = res.file;
  state.formData.projectProposalArr = res.file;
  formRef.value.clearValidate();
};

const handlePreview = (item: any) => {
  if (item.response) {
    window.open(
      `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
    );
  } else {
    window.open(
      `${location.origin}${location.pathname}#/online?uuidFile=${item.uuidFile}&fileName=${item.fileName}`
    );
  }
};

// 初始化请求
const initProjectTypeList = async () => {
  try {
    const params = {
      dicType: "rd_project_type"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectTypeArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const initPrincipalCompanyList = async () => {
  try {
    const params = {
      dicType: "rd_principal_cmpy"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      principalCompanyArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const initProjectApprovalTypeList = async () => {
  try {
    const params = {
      dicType: "rd_pro_approve_max_type"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectApproveTypeArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};
const initProjectApprovalTypeList2 = async () => {
  try {
    const params = {
      dicType: "rd_pro_approve_min_type"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectApproveTypeArr2.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

//获取项目状态
const initProjectStatusList = async () => {
  try {
    const params = {
      dicType: "rd_project_stage_code"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectStatusList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

async function getTableLeaderData(query = "") {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      name: query
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      userList.value = data.list.map(item => {
        return {
          id: item.id,
          name: item.name + (item.deptName ? "-" + item.deptName : "-无"),
          phoneNum: item.phoneNum,
          email: item.email,
          companyName: item.deptName
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

async function getTableLeaderData2(query = "") {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      name: query
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      userList2.value = data.list.map(item => {
        return {
          id: item.id,
          name: item.name + (item.deptName ? "-" + item.deptName : "-无"),
          phoneNum: item.phoneNum,
          email: item.email,
          companyName: item.deptName
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

//

const goBack = async (flag = true) => {
  console.log(flag);
  router.push("/project/filings");
};

const handleSubmit = async () => {
  state.saveLoading = true;
  const flag = await handleSave(false, "2");
  if (flag == null) {
    state.saveLoading = false;
    return;
  }
  if (!flag) {
    if (route.query.instanceId) {
      flowPassSubmit();
    } else {
      flowSumbitStart();
    }
  }
};

const flowSumbitStart = async () => {
  await approveProject(route.query.id);

  await submitStage(route.query.id);

  flowStartData.formBaseInfo.billName =
    state.formData.projectName + "-项目建档-审批流程";
  flowStartData.formBaseInfo.projectName = state.formData.projectName;

  flowStartData.flowFormData.flowTypeCode = state.flowType;

  flowStartData.formBaseInfo.projectManageId = state.projectManageId;
  flowStartData.formBaseInfo.id = state.projectManageId;

  flowStartData.flowFormData.projectManageId = state.projectManageId;
  flowStartData.flowFormData.businessId = state.projectManageId;
  flowStartData.formSubMap.flowType = state.flowType;
  flowStartData.formSubMap.assignee = state.leaderId;

  const { code, message } = await flowStart(flowStartData);
  if (code === 200) {
    state.saveLoading = false;
    NotifMessage.success(message);
    goBack();
  }
};

const flowPassSubmit = async () => {
  flowPassData.flowFormData.approvalComments = "";
  flowPassData.flowFormData.approvalResult = "1"; //同意：1，不同意：0
  flowPassData.flowFormData.remarks = "";
  flowPassData.flowFormData.flowTypeCode = state.flowType;
  flowPassData.formSubMap.opinion = ``;
  flowPassData.tmpStorage.valueJson = JSON.stringify(flowPassData.formSubMap);
  const info = storageLocal.getItem("rdms-info");
  const userId = info?.userId;
  flowPassData.tmpStorage.handlerId = userId;
  flowPassData.formBaseInfo.acceptUsers = state.leaderId;
  flowPassData.formSubMap.assignee = state.leaderId;
  flowPassData.formSubMap.isChargehand = "1";
  flowPassData.formSubMap.flowType = state.flowType;
  const { code, message } = await flowSubmit(flowPassData);
  if (code === 200) {
    NotifMessage.success(message);
    router.push("/approval/todo");
    // goBack();
  } else {
    NotifMessage.error(message);
  }
};

const getSubmitParams = () => {
  const copyFormData = cloneDeep(state.formData);
  copyFormData.kyFiles = JSON.stringify(copyFormData.kyFiles);
  delete copyFormData.kyFilesArr;
  copyFormData.projectTypeCode = state.formData.projectTypeCode.dicCode;
  copyFormData.projectTypeName = state.formData.projectTypeCode.dicValue;

  // copyFormData.approveTypeMaxCode = state.formData.approveTypeMaxCode.dicCode;
  // copyFormData.approveTypeMaxName = state.formData.approveTypeMaxCode.dicValue;

  // copyFormData.approveTypeMinCode = state.formData.approveTypeMinCode.dicCode;
  // copyFormData.approveTypeMinName = state.formData.approveTypeMinCode.dicValue;

  copyFormData.projectLeaderId = state.formData.projectLeaderId.id;
  copyFormData.projectLeaderName = state.formData.projectLeaderId.name;
  copyFormData.ext3 = copyFormData.projectOwner.id;
  copyFormData.ext4 = copyFormData.projectOwner.name;
  copyFormData.projectMemberList.forEach(el => {
    delete el.user;
  });

  // copyFormData

  const { query } = unref(route);
  copyFormData.id = query.id;
  copyFormData["principalCompanyCode"] =
    state.formData.principalCompanyCode.dicCode;
  copyFormData["principalCompanyName"] =
    state.formData.principalCompanyCode.dicValue;

  return copyFormData;
};

const handleSave = async (flag = true, status: string): Promise<any> => {
  if (state.formData.filgsLxFilesArr.length == 0) {
    NotifMessage.warning("请上传立项文档");
    return;
  }
  // if (state.formData.filgsYsFilesArr.length == 0) {
  //   NotifMessage.warning("请上传验收文档");
  //   return;
  // }
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));

  if (isValid) {
    state.saveLoading = true;
    const { query } = unref(route);
    const params = getSubmitParams();
    params["saveStatus"] = status;
    params["isFilings"] = "2";
    params["scientificAchv"] = state.scientifics.join(",");
    if (query.mode === "edit") {
      params.clickStage = "10";
      const { code, message } = await postProjectUpdate(params);

      if (code === 200) {
        if (flag) {
          state.saveLoading = false;
          NotifMessage.success(message);
          goBack();
          return true;
        } else {
          return false;
        }
      }
    } else {
      const { code, message, data } = await postProjectAdd(params);
      if (code === 200) {
        route.query.id = data;
        state.projectManageId = data + "";
        if (flag) {
          state.saveLoading = false;
          NotifMessage.success(message);
          goBack();
          return true;
        } else {
          return false;
        }
      }
    }
  }
};

const changeLeader = item => {
  if (item !== "") {
    state.leaderId = item.id;
    state.formData.projectLeaderPhone = item.phoneNum;
    state.formData.projectLeaderEmail = item.email;
    state.formData.projectMemberList[0] = {
      name: item.name.split("-")[0],
      user: item,
      isEmp: item.isEmp,
      id: item.id,
      userId: item.id,
      department: item.companyName,
      ext1: "项目负责人",
      leader: true
    };
  }
};
const changeOwner = item => {
  if (item !== "") {
    state.ownerId = item.id;
    state.formData.projectContactPhone = item.phoneNum;
    state.formData.projectContactEmail = item.email;
    state.formData.ext3 = item.id;
    state.formData.ext4 = item.name;
    state.formData.projectMemberList[1] = {
      name: item.name.split("-")[0],
      user: item,
      isEmp: item.isEmp,
      userId: item.id,
      id: item.id,
      department: item.companyName,
      ext1: "项目联系人",
      leader: true
    };
  }
};

const getScientific = async (query = "") => {
  const { code, data } = await postScientificList({
    scientificScouce: "1",
    ...{ kyName: query },

    ...{
      pageNum: 1,
      pageSize: 0
    }
  });
  if (code === 200) {
    state.scientificList = data.list;
    // model.tableData = data.list;
    // model.total = data.rows;
  }
};

onMounted(() => {
  const { query } = unref(route);
  if (query.id) {
    state.projectManageId = query.id as any;
    showProjectNumber.value = true;
    initGetProjectInfo(query.id as string);
    getScientific();
  }
});

const initGetProjectInfo = async (id: number | string) => {
  const { code, data } = await getProjectInfo({ id });
  if (code === 200) {
    // debugger
    const copyFormData = cloneDeep(data);
    state.formData.saveStatus = copyFormData.saveStatus;

    state.isSubmit =
      (copyFormData.stageApproveStatus === "1" ||
        copyFormData.stageApproveStatus === "4") &&
      (copyFormData.saveStatus === "3" || copyFormData.saveStatus === "8");

    state.formData = copyFormData;
    state.formData.projectTypeCode = {
      dicCode: copyFormData.projectTypeCode,
      dicValue: copyFormData.projectTypeName
    };

    // state.formData.approveTypeMaxCode = {
    //   dicCode: copyFormData.approveTypeMaxCode,
    //   dicValue: copyFormData.approveTypeMaxName
    // };
    // state.formData.approveTypeMinCode = {
    //   dicCode: copyFormData.approveTypeMinCode,
    //   dicValue: copyFormData.approveTypeMinName
    // };
    state.formData.principalCompanyCode = {
      dicCode: copyFormData.principalCompanyCode,
      dicValue: copyFormData.principalCompanyName
    };

    state.leaderId = copyFormData.projectLeaderId;
    state.ownerId = copyFormData.ext3;

    state.formData.projectOwner = {
      id: +copyFormData.ext3,
      name: copyFormData.ext4
    };
    state.formData.projectLeaderId = {
      id: +copyFormData.projectLeaderId,
      name: copyFormData.projectLeaderName
    };

    userList.value = [
      state.formData.projectLeaderId,
      state.formData.projectOwner
    ];

    userList2.value = [
      state.formData.projectLeaderId,
      state.formData.projectOwner
    ];

    if (copyFormData.kyFiles) {
      state.formData.kyFiles = JSON.parse(copyFormData.kyFiles as any);
      defaultFileList.value = state.formData.kyFiles;
      defaultFileList.value.map(el => {
        el["name"] = el.fileName;
      });
    } else {
      state.formData.kyFiles = [];
    }

    if (copyFormData.filgsKyFilesArr) {
      defaultkxxFileList.value = state.formData.filgsKyFilesArr;
      defaultkxxFileList.value.map(el => {
        el["name"] = el.fileName;
      });
    } else {
      state.formData.filgsKyFilesArr = [];
    }

    if (copyFormData.filgsLxFilesArr) {
      defaultLXFileList.value = state.formData.filgsLxFilesArr;
      defaultLXFileList.value.map(el => {
        el["name"] = el.fileName;
      });
    } else {
      state.formData.filgsLxFilesArr = [];
    }

    if (copyFormData.filgsSsFilesArr) {
      defaultSSFileList.value = state.formData.filgsSsFilesArr;
      defaultSSFileList.value.map(el => {
        el["name"] = el.fileName;
      });
    } else {
      state.formData.filgsSsFilesArr = [];
    }
    if (copyFormData.filgsYsFilesArr) {
      defaultYSFileList.value = state.formData.filgsYsFilesArr;
      defaultYSFileList.value.map(el => {
        el["name"] = el.fileName;
      });
    } else {
      state.formData.filgsYsFilesArr = [];
    }
    if (copyFormData.filgsHpjFilesArr) {
      defaultHPJFileList.value = state.formData.filgsHpjFilesArr;
      defaultHPJFileList.value.map(el => {
        el["name"] = el.fileName;
      });
    } else {
      state.formData.filgsHpjFilesArr = [];
    }

    state.scientifics = copyFormData.scientificAchvs.map(el => el.id);
    state.scientificTableList = copyFormData.scientificAchvs;

    // <template #default="{ row }"> {{ row.name }}-{{ row.legal }} </template>
    if (copyFormData.projectProposalArr) {
      defaultProposaFileList.value = copyFormData.projectProposalArr;
      defaultProposaFileList.value.map(el => {
        el["name"] = el.fileName;
      });
      // state.formData.projectProposalArr=
    } else {
      state.formData.projectProposalArr = [];
    }
    getStep();
  }
};

const jump = item => {
  const local = location.href.split("#")[0];
  let path = "";
  switch (item.kyTypeName) {
    case "专利":
      path = "#/document/scientific/patent";
      break;
    case "软件著作":
      path = "#/document/scientific/software";
      break;
    case "论文":
      path = "#/document/scientific/paper";
      break;
    case "专著":
      path = "#/document/scientific/book";
      break;
    case "标准":
      path = "#/document/scientific/standard";
      break;
    case "科技奖励":
      path = "#/document/scientific/award";
      break;
    case "科技制度建设":
      path = "#/document/scientific/building";
      break;
    default:
      path = "#/document/scientific/other";
      window.open(
        `${local}${path}?id=${item.id}&projectNum=${item.projectManageCode}&mode='look'`
      );
      return;
  }

  window.open(
    `${local}${path}?id=${item.kyId}&projectNum=${item.projectManageCode}&mode='look'`
  );
};
//查询流程审批记录
const getApproveHistoryList = async () => {
  const instanceId = route.query.instanceId;
  if (instanceId) {
    const { code, data } = await getApproveHistory(instanceId);
    if (code === 200) {
      approveRecord.value = data;
    }
  }
};

// 获取项目类型
const isApproval = route.query.mode === "look" ? true : false;
initProjectStatusList();
initProjectTypeList();
initProjectApprovalTypeList();
initProjectApprovalTypeList2();
initPrincipalCompanyList();
if (route.query.instanceId) {
  getApproveHistoryList();
}
</script>

<style scoped lang="scss">
.card-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-btn {
    font-size: 14px;
    cursor: pointer;
  }
}

.btnClass {
  margin-bottom: 8px;
}

.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  overflow-x: hidden;
  overflow-y: hidden;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// #tree-option
#tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}

// #tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
#tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}

.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}

#default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

#default-option {
  padding: 0 10px;
}

.des-p {
  color: #a7a3a3;
  font-size: 12px;
}

.milepost-box {
  border: 1px solid #d8dce6;

  .milepost-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    background: #4f9dff0c;
    text-indent: 16px;
    margin-bottom: 20px;

    .close {
      position: absolute;
      right: 20px;
      top: 12px;
      color: red;
      cursor: pointer;
      font-size: 16px;
    }
  }
}

.p-text {
  line-height: 32px;
  font-size: 14px;
}

:deep .approve-code .el-form-item__content {
  margin: 0 !important;
}

.steps {
  &:deep .el-step__title {
    font-size: 12px;
    line-height: 20px;
    margin-top: 12px;
  }

  // 已完成配置
  &:deep .el-step__title.is-success {
    color: #f9b05d; // 中文字体颜色
  }

  &:deep .el-step__head.is-success {
    color: #fff; // 图标颜色

    .el-step__icon.is-text {
      border-color: #f9b05d; // 圆圈边框
      background-color: #f9b05d; // 圆框背景色
    }

    .el-step__line {
      background-color: #f9b05d; // 已完成直线颜色
    }
  }

  // 正在进行中
  &:deep .el-step__head.is-process {
    color: #f9b05d; // 图标颜色

    // color: red; // 图标颜色
    .el-step__icon.is-text {
      border-color: #f9b05d; // 圆圈边框
      background-color: #fff; // 圆框背景色
    }

    .el-step__icon-inner {
      // display: none;
      width: 16px;
      height: 16px;
      background: #f9b05d;
      border-radius: 50%;
    }
  }

  // 未执行
  &:deep .el-step__head.is-wait {
    // color: #f9b05d; // 图标颜色
    // .el-step__icon.is-text {
    //   border-color: #f9b05d; // 圆圈边框
    //   background-color: #fff; // 圆框背景色
    //
    height: 24px;

    .el-step__icon-inner {
      display: none;
    }
  }
}
</style>
